import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;

@WebFilter(filterName = "loginFilter",urlPatterns={"/login"})
public class loginFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        // 每次执行都新建一个连接
	String URL=(String)getServletContext().getInitParameter("db.url");
	String NAME=(String)getServletContext().getInitParameter("db.user");
	String PASSWORD=(String)getServletContext().getInitParameter("db.password");
        try (Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD)) {

	    Statement stmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);

            ResultSet rs = stmt.executeQuery("select * from user where username='"+req.getParameter("username")+"'");

	    String inputpasswd=null;
            if(rs.next()) 
	       	inputpasswd = rs.getString("passwd");
	    System.out.println(inputpasswd+req.getParameter("passwd"));
	    if(inputpasswd ==null || inputpasswd.equals(req.getParameter("passwd").toString()) == false){
		System.out.println("inside the passwd check");
		HttpSession session = req.getSession(true);
		session.setAttribute("error", "login");
		try{
		    req.getRequestDispatcher("error.jsp").forward(req,res);
		}catch (ServletException e){
		    e.printStackTrace();
		}
	    }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
